<template>
  <div class=''>
    <!--  -->
    <Bootstrap v-bind:BootstrapTitle="BootstrapTitle"></Bootstrap>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 对话框 -->
      <el-dialog title="图片预览" :visible.sync="pictureDialogVisible" width="45%">
        <img :src="pictureUrl" alt="" width="60%">
      </el-dialog>
      <!-- 提示 -->
      <el-alert :closable="false" title="消息提示的文案" type="info" center show-icon>
      </el-alert>
      <!-- 步骤条 -->
      <el-steps align-center class="steps" :space="200" :active="activeIndex-0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>

      </el-steps>
      <!-- 标签页 -->
      <el-form :model="addRuleForm" :rules="addRules" ref="addRuleForm" label-width="100px" label-position="top">
        <el-tabs v-model="activeIndex" :tab-position="'left'" :before-leave="TabChangLeave" @tab-click="tabClicked">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addRuleForm.goods_name">
              </el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addRuleForm.goods_price">
              </el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addRuleForm.goods_weight">
              </el-input>
            </el-form-item>

            <el-form-item label="商品库存" prop="goods_number">
              <el-input type="number" v-model="addRuleForm.goods_number">
              </el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader v-model="addRuleForm.goods_cat" :props="cateProps" :options="Classoptions"
                expandTrigger='hover' @change="handleChange">
              </el-cascader>
            </el-form-item>

          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in ParamsList" :key="item.attr_id">

              <el-checkbox-group v-model="item.attr_vals">

                <el-checkbox border :label="cb" v-for="(cb,i) in item.attr_vals" :key="i"></el-checkbox>

              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTabelData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action图片上传地址 -->
            <el-upload :action="upLoadUrl" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture"
              :headers="headersObj" :on-success="handleUpPictuerSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addRuleForm.goods_introduce">

            </quill-editor>
            <!-- 按钮 -->
            <el-button class="aa" type="warning" size="small" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import Bootstrap from "../../component/component/Bootstrap";
import _ from "lodash";
export default {
  name: "",
  components: {
    Bootstrap,
  },
  data() {
    return {
      BootstrapTitle: {
        first: "商品管理",
        second: "/goods",
        third: "商品列表",
        Five: "添加商品",
      },
      activeIndex: "0",
      addRuleForm: {
        goods_name: "",
        goods_price: "10",
        goods_weight: "10",
        goods_number: "10",
        goods_introduce: "",
        goods_cat: [],
        pics: [],
        attrs: [],
      },
      addRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
      },
      Classoptions: [],
      cateProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      ParamsList: [], //many
      onlyTabelData: [], //only
      upLoadUrl: "http://timemeetyou.com:8889/api/private/v1/upload",
      headersObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      pictureUrl: "",
      pictureDialogVisible: false,
    };
  },
  created() {
    this.getGoodsClassList();
  },
  methods: {
    // getGoodsClassList
    async getGoodsClassList() {
      let res = await this.$http.get("categories");
      if (res.data.meta.status !== 200) {
        return;
      } else {
        this.Classoptions = res.data.data;
      }
    },
    handleChange() {
      if (this.addRuleForm.goods_cat.length !== 3) {
        this.addRuleForm.goods_cat = [];
      }
    },
    TabChangLeave(activeName, oldActiveName) {
      if (this.addRuleForm.goods_cat.length !== 3 && oldActiveName === "0") {
        this.$message.error("请先填写商品参数");
        return false;
      }
    },
    async tabClicked() {
      console.log(this.activeIndex);
      if (this.activeIndex === "1") {
        // console.log('动态参数面板');
        let res = await this.$http.get(`categories/${this.cateID}/attributes`, {
          params: { sel: "many" },
        });
        //  console.log(this.ParamsList, "ParamsList");
        if (res.data.meta.status !== 200) {
          this.$message.error(res.data.meta.msg);
        } else {
          res.data.data.forEach((item) => {
            item.attr_vals =
              item.attr_vals.length === "0" ? [] : item.attr_vals.split(" ");
          });
          this.ParamsList = res.data.data;
          // console.log(this.ParamsList, "this.ParamsList");
        }
      } else if (this.activeIndex === "2") {
        let res = await this.$http.get(`categories/${this.cateID}/attributes`, {
          params: { sel: "only" },
        });
        console.log(res, "res158");
        if (res.data.meta.status !== 200) {
          this.$message.error(res.data.meta.msg);
        } else {
          this.onlyTabelData = res.data.data;
        }
      }
    },
    // handlePreview预览图片处理
    handlePreview(file) {
      this.pictureDialogVisible = true;
      this.pictureUrl = file.response.data.url;
    },
    // 移除图片处理
    handleRemove(file) {
      console.log(file, "file");
      const filePath = file.response.data.tmp_path;
      const i = this.addRuleForm.pics.findIndex((x) => x.pic === filePath);
      this.addRuleForm.pics.splice(i, 1);
      console.log(this.addRuleForm, " this.addRuleForm.");
    },
    // 图片上传成功
    handleUpPictuerSuccess(response) {
      // console.log(response, "response");
      const picInfo = { pic: response.data.tmp_path };
      this.addRuleForm.pics.push(picInfo);
    },
    // addGoods
    addGoods() {
      console.log(this.addRuleForm, "=========!!!!!!!!!!1");
      this.$refs.addRuleForm.validate((valid) => {
        if (!valid) return this.$message.error("请填写必填信息");
        const from = _.cloneDeep(this.addRuleForm);
        from.goods_cat = from.goods_cat.join(",");

        this.ParamsList.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          this.addRuleForm.attrs.push(newInfo);
        });
        // 静态
        this.onlyTabelData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          this.addRuleForm.attrs.push(newInfo);
        });
        from.attrs = this.addRuleForm.attrs;
        console.log(from, "from");
        this.addGoodsData(from);
      });
    },
    // 添加商品请求
    async addGoodsData(par) {
      let res = await this.$http.post("goods", par);
      if (res.data.meta.status !== 201) {
        par.goods_cat = [];
        return this.$message.error(res.data.meta.msg);
      } else {
        this.$message.success(res.data.meta.msg);
        this.$router.push("/goods");
      }
    },
  },
  computed: {
    cateID() {
      if (this.addRuleForm.goods_cat.length === 3) {
        return this.addRuleForm.goods_cat[2];
      } else {
        return null;
      }
    },
  },
};
</script>
<style lang='less' scoped>
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
.aa {
  margin-top: 10px;
}
</style>